﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.ComponentModel;

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;
using System.Collections.Specialized;
using HospitalSystem.Core;

namespace HospitalSystem
{
    public partial class rightsinfoshow : System.Web.UI.Page
    {
        private RegisterLog _RL;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CID"] == null)
            {

                MessageBoxurl("กรุณากดค้นหา หรือลงทะเบียนเด็กก่อน", "findchild.aspx");

            }
            else
            {

                String ShowValue = (string)Session["CID"];
                cid_label.Text = ShowValue;

                _RL = new RegisterLog();


                show_Images();

                show_Images2();
                show_Images3();

                if (!IsPostBack)
                {
                    showsession();
                    _RL.radiomedicalcare(medicalcare);

                    _RL.radioyesno_1(yesno1);
                    _RL.radioyesno_2(yesno2);







                    _RL.loaddatarightsinfoshow(cid_label, MedicalIDcardl, Dateofissuel, Dateofexpl, PrimaryCareClinicl, CareClinicForwardl, NumberDisabilitieIDl, NumberDisabilitieIDdatel, NumberDisabilitieIDexpl);

                    _RL.loaddatadropdownDisabilityTypeshow(DisabilityTypel, cid_label);
                    _RL.loaddataradiomedicalcareshow(cid_label, medicalcarel);

                    _RL.loaddataradioDisabilityAllowanceshow(cid_label, yesno1l);
                    _RL.loaddataradioCouponStudyshow(cid_label, yesno2l);
                }
            }


        }



        protected void showsession()
        {
            String ShowValue = (string)Session["CID"];
            cid_label.Text = ShowValue;




        }

        private void MessageBoxurl(string msg, string urld)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "');" + "window.location.href='" + urld + "';" + "</script>";
            Page.Controls.Add(lbl);
        }

        public void show_Images()
        {
            string sj = "";



            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);

            SqlCommand CmdSql2 = new SqlCommand("SELECT Child_Pic FROM [Person] where cid=@CID", conn);
            conn.Open();
            CmdSql2.Parameters.AddWithValue("@CID", Session["CID"]);

            SqlDataReader reader2 = CmdSql2.ExecuteReader();

            if (reader2.Read())
            {
                sj = reader2["Child_Pic"].ToString();
            }
            else
            {
                sj = "~/pic/profile/nopic.jpg";
            }
            conn.Close();
            reader2.Close();


            Image1.ImageUrl = (sj);
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            Panel2.Visible = true;
            _RL.loaddatarightsinfo(cid_label, MedicalIDcard, Dateofissue, Dateofexp, PrimaryCareClinic, CareClinicForward, NumberDisabilitieID, NumberDisabilitieIDdate, NumberDisabilitieIDexp);

            _RL.loaddatadropdownDisabilityType(DisabilityType);
            _RL.loaddataradiomedicalcare(cid_label, medicalcare);

            _RL.loaddataradioDisabilityAllowance(cid_label, yesno1);
            _RL.loaddataradioCouponStudy(cid_label, yesno2);
            _RL.loaddataDisabilityType(cid_label, DisabilityType);

            Panel1.Visible = false;
        }

        protected void submit(object sender, EventArgs e)
        {
            //ok
            _RL.insertregdatarightsinfo(cid_label, MedicalIDcard.Text, Dateofissue.Text, Dateofexp.Text, PrimaryCareClinic.Text, CareClinicForward.Text, NumberDisabilitieID.Text, NumberDisabilitieIDdate.Text, NumberDisabilitieIDexp.Text, medicalcare, yesno1, yesno2, DisabilityType);
            ImageUpload_f();
            Imagesavetodb2();
            Response.Redirect("rightsinfoshow.aspx");
        }



        protected void Imagesavetodb()
        {
            String pic;
            pic = "https://sp01.blob.core.windows.net/note/" + Session["CID"] + "";


            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;

            SqlConnection scon = new SqlConnection(constr);
            SqlCommand cmd22 = new SqlCommand("UPDATE [ExistingWelfare] set DisableCardIDPic=@FilePath where CID=@Iddek", scon);
            cmd22.Parameters.AddWithValue("@Iddek", Session["CID"]);

            cmd22.Parameters.AddWithValue("@FilePath", pic);

            scon.Open();
            cmd22.ExecuteNonQuery();
            scon.Close();
        }
        protected void ImageUpload_f()
        {

            if (imageFile.HasFile)
            {
                Imagesavetodb();


                this.SaveImage(
                  Guid.NewGuid().ToString(),
                  (string)Session["CID"],
                  (string)Session["CID"],
                  (string)Session["CID"],
                  imageFile.FileName,
                  imageFile.PostedFile.ContentType,
                  imageFile.FileBytes
                );

                //RefreshGallery();
                Imagesavetodb();
            }
            else
            {
            }


        }


        private void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
        {
            // Create a blob in container and upload image bytes to it
            var blob = this.GetContainer().GetBlobReference(name);

            blob.Properties.ContentType = contentType;

            // Create some metadata for this image
            var metadata = new NameValueCollection();
            metadata["Id"] = id;
            metadata["Filename"] = fileName;
            metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
            metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
            metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

            // Add and commit metadata to blob
            blob.Metadata.Add(metadata);
            blob.UploadByteArray(data);


        }


        private CloudBlobContainer GetContainer()
        {
            // Get a handle on account, create a blob service client and get container proxy
            //var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            //var client = account.CreateCloudBlobClient();
            //return blobClient.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container. 
            CloudBlobContainer container = blobClient.GetContainerReference("note");

            // Create the container if it doesn't already exist.
            BlobContainerPermissions permission = new BlobContainerPermissions();
            permission.PublicAccess = BlobContainerPublicAccessType.Off;
            SharedAccessPolicy policy = new SharedAccessPolicy();
            policy.Permissions = SharedAccessPermissions.None;
            permission.SharedAccessPolicies.Add("abc", policy);

            //container.SetPermissions(permission);

            container.CreateIfNotExist();
            return container;
        }













        protected void Imagesavetodb2()
        {
            String pic;
            pic = "https://sp01.blob.core.windows.net/medicalcare/" + Session["CID"] + "";


            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;

            SqlConnection scon = new SqlConnection(constr);
            SqlCommand cmd22 = new SqlCommand("UPDATE [ExistingWelfare] set InsuranceCardPic=@FilePath where CID=@Iddek", scon);
            cmd22.Parameters.AddWithValue("@Iddek", Session["CID"]);

            cmd22.Parameters.AddWithValue("@FilePath", pic);

            scon.Open();
            cmd22.ExecuteNonQuery();
            scon.Close();
        }


        protected void ImageUpload_2()
        {

            if (FileUpload3.HasFile)
            {



                this.SaveImage2(
                  Guid.NewGuid().ToString(),
                  (string)Session["CID"],
                  (string)Session["CID"],
                  (string)Session["CID"],
                  FileUpload3.FileName,
                  FileUpload3.PostedFile.ContentType,
                  FileUpload3.FileBytes
                );

                //RefreshGallery();
                Imagesavetodb2();
            }
            else
            {
            }

        }




        private void SaveImage2(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
        {
            // Create a blob in container and upload image bytes to it
            var blob2 = this.GetContainer2().GetBlobReference(name);

            blob2.Properties.ContentType = contentType;

            // Create some metadata for this image
            var metadata2 = new NameValueCollection();
            metadata2["Id"] = id;
            metadata2["Filename"] = fileName;
            metadata2["ImageName"] = String.IsNullOrEmpty(name) ? "  unknown" : name;
            metadata2["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
            metadata2["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

            // Add and commit metadata to blob
            blob2.Metadata.Add(metadata2);
            blob2.UploadByteArray(data);


        }


        private CloudBlobContainer GetContainer2()
        {
            // Get a handle on account, create a blob service client and get container proxy
            //var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            //var client = account.CreateCloudBlobClient();
            //return blobClient.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container. 
            CloudBlobContainer container = blobClient.GetContainerReference("medicalcare");

            // Create the container if it doesn't already exist.
            BlobContainerPermissions permission = new BlobContainerPermissions();
            permission.PublicAccess = BlobContainerPublicAccessType.Off;
            SharedAccessPolicy policy = new SharedAccessPolicy();
            policy.Permissions = SharedAccessPermissions.None;
            permission.SharedAccessPolicies.Add("abc", policy);

            //container.SetPermissions(permission);

            container.CreateIfNotExist();
            return container;
        }




        








        protected void uploadpic_Click(object sender, EventArgs e)
        {
          
     
        
        }





        public void show_Images2()
        {
            string sj = "";



            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);

            SqlCommand CmdSql2 = new SqlCommand("SELECT DisableCardIDPic FROM [ExistingWelfare] where cid=@CID", conn);
            conn.Open();
            CmdSql2.Parameters.AddWithValue("@CID", Session["CID"]);

            SqlDataReader reader2 = CmdSql2.ExecuteReader();

            if (reader2.Read())
            {
                sj = reader2["DisableCardIDPic"].ToString();
            }
            else
            {
                sj = "~/pic/profile/nopic.jpg";
            }
            conn.Close();
            reader2.Close();


            Image5.ImageUrl = (sj);
        }



        public void show_Images3()
        {
            string sj = "";



            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);

            SqlCommand CmdSql2 = new SqlCommand("SELECT InsuranceCardPic FROM [ExistingWelfare] where cid=@CID", conn);
            conn.Open();
            CmdSql2.Parameters.AddWithValue("@CID", Session["CID"]);

            SqlDataReader reader2 = CmdSql2.ExecuteReader();

            if (reader2.Read())
            {
                sj = reader2["InsuranceCardPic"].ToString();
            }
            else
            {
                sj = "~/pic/profile/nopic.jpg";
            }
            conn.Close();
            reader2.Close();


            Image4.ImageUrl = (sj);
        }



        }
    }
